package com.nineclock.security.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.security.mapper.UserMapper;
import com.nineclock.security.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    /**
     * 根据用户名 获取 User对象
     *
     * 1. 根据用户名从数据库获取 user信息
     * 2. 根据查询到的用户信息，封装成UserDetails 返回
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        //根据用户名获取 User对象
        User user = userMapper.selectOne(wrapper);

        UserDetails userDetails =
                new org.springframework.security.core.userdetails.User(
                        user.getUsername(), user.getPassword(),
                        AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));



        return userDetails;
    }
}
